#include "timing.h"
#include <QFile>
#include <QDateTime>
#include <QTextStream>
Timing::Timing(QWidget *parent)
    : QDialog(parent)
{
	ui.setupUi(this);
    int width;
    QRect rect;
    rect=ui.tblResults->frameGeometry();
    width=rect.width()-45; // - size of row label
    
    ui.txtFilename->setText("/home/nandakiran/indexes/tag.index.query.1");
    ui.txtOutputFilename->setText("/home/nandakiran/indexes/tag.index.query.out.1");
    
    ui.tblResults->setColumnWidth ( 0, (int)(0.40*width));
    ui.tblResults->setColumnWidth ( 1, (int)(0.15*width));
    ui.tblResults->setColumnWidth ( 2, (int)(0.15*width));
    ui.tblResults->setColumnWidth ( 3, (int)(0.15*width));
    ui.tblResults->setColumnWidth ( 4, (int)(0.15*width));

}

Timing::~Timing()
{

}

void Timing::dowork() {
	QString filename=ui.txtFilename->text();
	QTableWidgetItem *cell;
    QString line;
    QFile file( filename );
    if ( !file.open( QIODevice::ReadOnly ) ) 
            return;
    QTextStream ts( &file );
    do {
    	if (ts.atEnd())
    		return;
    	line=ts.readLine();
    } while (line.startsWith("#"));
    //repeats=line.toInt();
    while (ui.tblResults->rowCount()>0) 
    	ui.tblResults->removeRow(0);
    
    ui.tblResults->insertRow(ui.tblResults->rowCount());
    cell = new QTableWidgetItem(line);
    ui.tblResults->setItem(ui.tblResults->rowCount()-1,0,cell);
    repeats=1;
    while (!ts.atEnd()) {
    	line=ts.readLine();
    	cell = new QTableWidgetItem(line);
    	ui.tblResults->insertRow(ui.tblResults->rowCount());
    	ui.tblResults->setItem(ui.tblResults->rowCount()-1,0,cell);
    }
    ui.lblDetail->setText(QString("Repetitions: %1").arg(repeats));
    file.close();
}

void Timing::doactualquery() {
    long indexsize;
    long tagsize;
    long elapse,val;
    int i,j;
    QTime timetaken;
    QString st,query;
    linkedlist *files,*tags;

    randomize();

/*
    //--------------------------------------------------------------      
    // Add/remove tags timings
    initializetest();
   	printf("Creating Test files\n");
   	addtestfiles(10000);
   	printf("Creating Test files trie\n");     
   	maketestfilestrie();
   	printf("Add/Remove Tags\n");
   	timetaken = QTime(0,0);
   	timetaken.restart();
   	countoperations=0;
   	first1=0;
   	avg1=0;
   	for (i=0;i<500;i++) {
	 	printf("%d : ",i);
	  	j =(int) (rand()%5);
	  	switch (j) {
	  		case 0: case 3:
	      		//printf("Remove\n");
	     		// removerandomtags();break;
	  		case 1:
    	      	printf("Add Hierarchical\n");
	      		addrandomhiertags();break;
	  		case 2:	case 4: 
	      		printf("Add flat\n");
	      		addrandomtags(); break;
	  	}
	}
    printf("\n\n");

*/
    
    timetaken = QTime(0,0);
    timetaken.restart();
    countoperations=0;
    first1=0;
    avg1=0;
    QTime temptime;
    char filename[600];
    linkedlist *lt;
    char *chr;
    for (i=0;i<1000;i++) {
    	lt=clientrandomfile();
    	if (!(lt->isEmpty())) {
    		chr=lt->remove();
    		strcpy(filename,chr);
    		free(chr);
    	}
    	delete lt;
    	lt = clientrandomtag();
    	if ((!(lt->isEmpty())) && (strlen(filename)!=0)) {
			temptime = QTime(0,0);
			temptime.restart();
			clientaddtags(filename,lt);
			elapse=temptime.elapsed();
			countoperations++;
			if (countoperations==1)
				first1=elapse;
			avg1=((avg1*(countoperations-1)+elapse)/countoperations);
			lt->removeAll();
    	}
    	delete lt;
    }
    elapse=timetaken.elapsed(); 
    printf("Total Time Taken  : %ld \n", elapse);
    printf("Number of operations : %ld \n",countoperations);
    printf("Average  Overall, Individual : %ld , %ld \n",(elapse/countoperations),avg1);
    ui.lblAddRemove->setText(QString("Add/Remove Operations\nTotal Time Taken  : %1 \nNumber of operations : %2 \nAverage  Overall, Individual : %3 , %4 \n").arg(elapse).arg(countoperations).arg((elapse/countoperations)).arg(avg1));
//    freeup();

//---------------------------------------------------------------------
// The actual querying is below...........................
    first1=0;
    avg1=0;
    tagsize=clienttagsinindex();
    indexsize=clientfilesinindex();
    ui.lblDetail->setText(QString("Repetitions: %1 Index Size: %2  Tags : %3").arg(repeats).arg(indexsize).arg(tagsize));
    printf("%s \n",QString("Repetitions: %1 Index Size: %2  Tags : %3").arg(repeats).arg(indexsize).arg(tagsize).toAscii().data());
    tags=new linkedlist();
    for (j=0;j<repeats;j++) {
    	printf("\n\n Iteration %d\n",j+1);
    	printf("----------------------\n");
    	QTableWidgetItem *tmpitem;
    
    	for (i=0;i<ui.tblResults->rowCount();i++)  {
    		ui.tblResults->repaint();
    		query=(ui.tblResults->item(i,0))->text(); 
    		tags=new linkedlist();
    		QStringList l;
    		l = query.trimmed().split(' ');
    		for ( QStringList::Iterator it = l.begin(); it != l.end(); ++it )
    			tags->add(((*it).toAscii()).data());
    		timetaken = QTime(0,0);
    		timetaken.restart();
    		count1=0;count2=0;
    		avg1=0;avg2=0;
    		first1=0;first2=0;
    		files=clientlistNfiles(tags);
    		//tmp=timedclientgetsuggestions();

    		indexsize=files->count();
    		elapse=timetaken.elapsed();
    		if (j>0) {
    			val=(ui.tblResults->item(i,2))->text().toInt();
    			val=val*j;
    			elapse+=val;
    			elapse/=(j+1);
    		}
    		st.setNum(elapse); 
    		
    		tmpitem=ui.tblResults->item(i,2);
    		if (tmpitem==NULL)
    			tmpitem = new QTableWidgetItem();
    		tmpitem->setText(st);
    		ui.tblResults->setItem(i,2,tmpitem);	  
    		
   		
    		st.setNum(indexsize); 	  
    		tmpitem=ui.tblResults->item(i,1);
    		if (tmpitem==NULL)
    			tmpitem = new QTableWidgetItem();
    		tmpitem->setText(st);
    		ui.tblResults->setItem(i,1,tmpitem);	  
    		
    		elapse=(first1+first2);
    		if (j>0) {
    			val=(ui.tblResults->item(i,3))->text().toInt();
    			val=val*j;
    			elapse+=val;
    			elapse/=(j+1);
    		}
    		st.setNum(elapse);
    		
    		tmpitem=ui.tblResults->item(i,3);
    		if (tmpitem==NULL)
    			tmpitem = new QTableWidgetItem();
    		tmpitem->setText(st);
    		ui.tblResults->setItem(i,3,tmpitem);	  
    		
    		if (count1+count2>0) 
    			elapse=((avg1*count1+avg2*count2)/(count1+count2));
    		else
    			elapse=0;
    		if (j>0) {
    			val=(ui.tblResults->item(i,4))->text().toInt();
    			val=val*j;
    			elapse+=val;
    			elapse/=(j+1);
    		}
    		st.setNum(elapse);
    		tmpitem=ui.tblResults->item(i,4);
    		if (tmpitem==NULL)
    			tmpitem = new QTableWidgetItem();
    		tmpitem->setText(st);
    		ui.tblResults->setItem(i,4,tmpitem);	  
    		//    	printf("%s \t\t %ld \t\t %d \t\t %d \t\t %d \n",(tblResults->text(i,0)).ascii(),indexsize,QString(tblResults->text(i,2)).toInt(),QString(tblResults->text(i,3)).toInt(),QString(tblResults->text(i,4)).toInt());
    	}
    	// printf("%s \t\t %ld \t\t %d \t\t %d \t\t %d \n",(tblResults->text(i,0)).ascii(),indexsize,QString(tblResults->text(i,2)).toInt(),QString(tblResults->text(i,3)).toInt(),QString(tblResults->text(i,4)).toInt());
    }
}

void Timing::writeback() {
	QString filename=ui.txtOutputFilename->text();
    QString line;
    int i,j;
    QFile file( filename );
    if ( !file.open( QIODevice::WriteOnly ) ) 
            return;
    QTextStream ts( &file );
    ts<< ui.lblDetail->text()<<"\n";
    ts<< ui.lblAddRemove->text()<<"\n";
    for (i=0;i<ui.tblResults->rowCount();i++)  {
    	for (j=0;j<ui.tblResults->columnCount();j++)
    		if (ui.tblResults->item(i,j)==NULL) 
    			ts<<"---\t";
    		else {
        		if (j==0) 
        			ts<<((ui.tblResults->item(i,j))->text().leftJustified(50,' ')).toAscii().data()<<'\t';
        		else {
        			ts<<((ui.tblResults->item(i,j))->text().rightJustified(5,' ')).toAscii().data()<<'\t';
        		}
    		}	
    	ts<<'\n';
    }
    file.close();
}

void Timing::on_btnOk_clicked() {
	dowork();
}

void Timing::on_btnDoQuery_clicked() {
	doactualquery();
}

void Timing::on_btnWrite_clicked() {
	writeback();
}
